const conn = require('../app/database')

class ThemeModel {
	async checkTheme(type) {
		const statement = `
      SELECT * FROM goods_theme WHERE theme_sign_name = ?
    `
		const [result] = await conn.execute(statement, [type])
		return result.length === 0 ? false : true
	}

	async getThemeList(type, offset, size) {
		const statement = `
      SELECT 
        gt.id themeId, gt.theme_name themeFullName, gt.theme_sign_name themeSignName,
        JSON_ARRAYAGG(
          JSON_OBJECT('goodsId', g.id, 'spuNo', g.spu_no, 'goodsName', g.goods_name, 'showImg', g.show_img, 'initialPrice', g.initial_price, 'newPrice', new_price, 'categoryId', category_id, 'themeId', g.theme_id, 'goodsDesc', g.goods_desc)
        ) goodsList
      FROM goods_theme gt 
      LEFT JOIN goods g ON gt.id = g.theme_id 
      WHERE gt.theme_sign_name = ?
      LIMIT ?, ?;
    `
    try {
      // 这里的 offset 和 size 都是 String 类型，不然会报错！？
      const [result] = await conn.execute(statement, [type, String(offset), String(size)])
		// const [result] = await conn.execute(statement, [type, 0, 8])
		  return result
    } catch (error) {
      console.log('error---', error);
    }

	}

	async getThemeListLength(type) {
		const statement = `
      SELECT 
        COUNT(*) goodsListLength
      FROM goods_theme gt 
      LEFT JOIN goods g ON gt.id = g.theme_id 
      WHERE gt.theme_sign_name = ?
      GROUP BY gt.id;  
    `
		const [result] = await conn.execute(statement, [type])
		return result
	}
}

module.exports = new ThemeModel()
